package cn.com.anypay.manager.service.auth.strategy.impl;

import cn.com.anypay.manager.miaoma.sysuser.SysUserEntity;
import cn.com.anypay.manager.service.SmsService;
import cn.com.anypay.manager.service.VerificationCodeService;
import cn.com.anypay.manager.service.auth.model.AuthRequest;
import cn.com.anypay.manager.service.auth.strategy.AbstractAuthStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.regex.Pattern;

/**
 * 短信验证码认证策略
 * 实现手机号短信验证码认证逻辑
 */
@Slf4j
@Component
public class SmsAuthStrategy extends AbstractAuthStrategy {

    @Autowired
    private VerificationCodeService verificationCodeService;

    @Autowired
    private SmsService smsService;

    /**
     * 手机号正则表达式
     */
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");

    @Override
    public String getAuthType() {
        return "sms";
    }

    @Override
    protected boolean doAuthenticate(AuthRequest request, SysUserEntity user,
                                   HttpServletRequest servletRequest) {
        // 验证短信验证码
        boolean codeValid = verificationCodeService.verifyCode(
            "sms_login", request.getIdentifier(), request.getCredential());

        if (!codeValid) {
            log.warn("短信验证码验证失败: phone={}", request.getIdentifier());
            return false;
        }

        return true;
    }

    @Override
    protected SysUserEntity findOrCreateUser(AuthRequest request, HttpServletRequest servletRequest) {
        String phone = request.getIdentifier();

        // 先尝试查找现有用户
        SysUserEntity user = sysUserService.getByPhone(phone);
        if (user != null) {
            return user;
        }

        // 如果用户不存在，创建新用户
        log.info("创建新用户: phone={}", phone);

        user = new SysUserEntity();
        user.setPhone(phone);
        user.setUsername(phone); // 使用手机号作为用户名
        user.setRealName("用户" + phone.substring(phone.length() - 4)); // 使用后4位作为真实姓名
        user.setStatus(1); // 启用状态
        user.setCreatedTime(LocalDateTime.now());
        user.setUpdatedTime(LocalDateTime.now());

        // 保存用户
        sysUserService.save(user);

        // 创建手机号认证记录
        sysUserAuthService.createPasswordAuth(user.getId(), phone, ""); // 短信认证不需要密码

        log.info("新用户创建成功: userId={}, phone={}", user.getId(), phone);
        return user;
    }

    @Override
    protected void validateRequest(AuthRequest request) {
        super.validateRequest(request);

        // 验证手机号格式
        if (!PHONE_PATTERN.matcher(request.getIdentifier()).matches()) {
            throw new IllegalArgumentException("手机号格式不正确");
        }

        // 验证验证码格式
        if (!request.getCredential().matches("\\d{6}")) {
            throw new IllegalArgumentException("验证码格式不正确");
        }
    }

    @Override
    public void sendVerificationCode(String identifier) {
        log.info("发送短信验证码: phone={}", identifier);

        // 验证手机号格式
        if (!PHONE_PATTERN.matcher(identifier).matches()) {
            throw new IllegalArgumentException("手机号格式不正确");
        }

        try {
            // 生成验证码
            String code = verificationCodeService.generateCode("sms_login", identifier);

            // 发送短信
            smsService.sendSms(identifier, "{\"code\":\"" + code + "\"}");

            log.info("短信验证码发送成功: phone={}", identifier);

        } catch (Exception e) {
            log.error("发送短信验证码失败: phone={}", identifier, e);
            throw new RuntimeException("发送短信验证码失败，请稍后重试", e);
        }
    }
}